#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <cerrno>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
//./ser port
int main(int argc, char **argv)

{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " port" << std::endl;
        return 1;
    }
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket error: " << errno << std::endl;
        return 2;
    }
    std::cout<<"socket() successful! sock number = "<<sock<<std::endl;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(atoi(argv[1]));

    socklen_t addrlen = sizeof(addr);
    if (bind(sock, (struct sockaddr *)&addr, addrlen) < 0)
    {
        std::cerr << "bind failed:" << errno << std::endl;
        return 3;
    }
    std::cout<<"bind succeeded "<<std::endl;

    char buf[1024];
    while (true)
    {
        memset(buf, 0, sizeof(buf));

        //需要直到接收谁的数据
        struct sockaddr_in peer_addr;
        memset(&peer_addr, 0, sizeof(peer_addr));
        socklen_t peer_len = sizeof(peer_addr);
        ssize_t sz = recvfrom(sock, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&peer_addr, &peer_len);

        std::cout<<"client ip :"<<inet_ntoa(peer_addr.sin_addr)<<" port:"<<ntohs(peer_addr.sin_port)<<std::endl;

        if (sz > 0) //接收成功
        {
            //当字符串处理
            buf[sz] = 0;
            std::cout << "client to server：" << buf << std::endl;

            //回射回去
            std::string echo_str = buf;
            echo_str += "<-------我是服务器来的数据";
            ssize_t cnt = sendto(sock, echo_str.c_str(), echo_str.size(), 0, (struct sockaddr *)&peer_addr, peer_len);
        }
        else
        {
            // error
        }
    }
    return 0;
}
